package com.iweb.controller;

import com.alibaba.fastjson.annotation.JSONType;
import com.common.context.RequestMapping;
import com.common.model.DataGrid;
import com.common.model.Page;
import com.iweb.pojo.Admin;
import com.iweb.service.AdminService;
import com.iweb.utils.JsonUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 商家用户信息的管理模块
 * 1. 新增用户
 * 2. 查询所有用户（分页）
 * 3. 撰取编辑用户
 */
// admin
@RequestMapping("admin")
public class AdminController {


    @RequestMapping("login")
    public String login(Admin admin, HttpServletRequest request) {
        AdminService adminService = new AdminService();
        Admin result = adminService.findUserByUsername(admin.getUsername());
        // 业务用户
        if (result == null) {
            request.setAttribute("message", "用户不存在");
            return "/admin/login.jsp";
        }
        // 判断密码
        if (!admin.getPassword().equals(result.getPassword())) {
            request.setAttribute("message", "密码错误");
            return "/admin/login.jsp";
        }
        // 保存用户到session
        HttpSession session = request.getSession();
        session.setAttribute("user", result);
        return "/admin/index.jsp";
    }

    @RequestMapping("findAdminList")
    // findAdminList
    public String findAdminList(Page page, HttpServletResponse response) {
        AdminService adminService = new AdminService();
        DataGrid<Admin> dataGrid = adminService.findAdminList(page);
        JsonUtil.writeJsonStr(response,dataGrid);
        return null;
    }

    @RequestMapping("addAdmin")
    // addAdmin
    public String addAdmin(Admin admin) {
        AdminService adminService = new AdminService();
        boolean flag = adminService.addAdmin(admin);
        if (flag) {
            // 注冊成功  indexAdmin.jsp
            return "/admin/indexAdmin.jsp";
        } else {
            // 如果重複返 indexAddAdmin.jsp
            return "/admin/indexAddAdmin.jsp";
        }

    }

    @RequestMapping("delete")
    public String deleteById(Admin admin){
        AdminService adminService = new AdminService();
        adminService.deleteById(admin.getAid());
        return "/admin/indexAdmin.jsp";
    }

    @RequestMapping("detail")
    public String detail(Admin admin,HttpServletResponse response){
        AdminService adminService = new AdminService();
        Admin data = adminService.findById(admin.getAid());
        JsonUtil.writeJsonStr(response,data);
        return null;
    }
}
